﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Threading;

namespace SharePointManagementStudio
{
    public partial class DownloadSolutions : Form
    {
        public DownloadSolutions()
        {
            InitializeComponent();
            
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

        }

        private void Main_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            List<String> w = new List<string>();
            try
            {
                SPFarm spf = SPFarm.Local;
                SPWebService spws = spf.Services.GetValue<SPWebService>("");
                int sitecount = spws.WebApplications.Count;

                foreach (SPWebApplication spwa in spws.WebApplications)
                {
                    try
                    {
                        w.Add(spwa.Sites[0].RootWeb.Url.ToString());
                        Thread.Sleep(50);
                    }
                    catch
                    {
                        //AppendText("error accured when connect to :" + spwa.Name.ToString() + " site collection is not found or site correpted.\n");
                    }
                }
            }
            catch
            {
                MessageBox.Show("An error eccored while connec to FARM.", "Error");
            }

            e.Result = w;
            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Value = 100;            
            toolStripProgressBar1.Value = 0;
            timer1.Stop();
            this.listBox1.DataSource = e.Result;
            checkBox1.Enabled = true; 
        }

        // Load all web application to Listbox control.
        private void Load_WebApplications()
        {
            listBox1.Items.Clear();   
            SPFarm spf = SPFarm.Local;
            SPWebService spws = spf.Services.GetValue<SPWebService>("");
            foreach (SPWebApplication spwa in spws.WebApplications)
            {
                listBox1.Items.Add(spwa.Name);
            }
        }


        // Load solution for selected application.
        private void Load_installed_solutions(String app)
        {
            SPSolutionCollection solutions = SPFarm.Local.Solutions;
            foreach (SPSolution solution in solutions)
            {
                try
                {
                    foreach (SPWebApplication webapp in solution.DeployedWebApplications)
                    {
                        //Console.WriteLine(webapp.Sites[0].RootWeb.Url.ToString() + "\n");    
                        if (solution.DeploymentState.ToString().ToLower() != "globaldeployed")
                        {
                            if (webapp.Sites[0].RootWeb.Url.ToString() == app.ToString())
                                checkedListBox1.Items.Add(solution.SolutionFile.Name);
                        }
                    }
                }
                catch { }
            }
            
        }

        // Load global deployed solution
        private void Load_Global_Deployed_Solutions()
        {
            SPSolutionCollection solutions = SPFarm.Local.Solutions;
            foreach (SPSolution solution in solutions)
            {              
                   
                        //Console.WriteLine(webapp.Sites[0].RootWeb.Url.ToString() + "\n");    
                        if (solution.DeploymentState.ToString().ToLower() == "globaldeployed")
                        {
                           
                                checkedListBox1.Items.Add(solution.SolutionFile.Name);
                        }
                  
              
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            checkedListBox1.Items.Clear();
            Load_installed_solutions(listBox1.SelectedItem.ToString());
        }



        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked == true)
            {
                listBox1.Enabled = false;
                this.checkedListBox1.Items.Clear();
                Load_Global_Deployed_Solutions();
            }
            else
            {
                listBox1.Enabled = true;
                this.checkedListBox1.Items.Clear();
                if (listBox1.SelectedItem != null)
                    Load_installed_solutions(listBox1.SelectedItem.ToString());
            }
        }

        private void buttonSaveAs_Click(object sender, EventArgs e)
        {
            

                }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)
            {
                toolStripProgressBar1.Value = 0;
            }
            toolStripProgressBar1.PerformStep();
        }

        private void toolStripButtonConnectFarm_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.RunWorkerAsync();
            timer1.Start(); 
        }

        private void toolStripButtonSaveAs_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            Boolean err = false; 
            if (result == DialogResult.OK)
            {
                string folderName = folderBrowserDialog1.SelectedPath;
                if (folderName != null)
                {

                    if (checkedListBox1.CheckedItems.Count != 0)
                    {

                        for (int x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++)
                        {
                            SPSolution mySolution = SPFarm.Local.Solutions[checkedListBox1.CheckedItems[x].ToString()];
                            string solname = string.Format(@"{0}\{1}", folderName, mySolution.SolutionFile.Name);
                            try
                            {
                                mySolution.SolutionFile.SaveAs(solname);
                            }
                            catch (Exception ex)
                            {
                                err = true; 
                                MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);        
                            }
                        }
                    }


                }
                if (err == false)
                {
                    MessageBox.Show("Save solution is successfully complated.",
                                    "Operation",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation,
                                    MessageBoxDefaultButton.Button1);
                }
            }
        }

        private void checkBoxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxSelectAll.Checked == true)
            {
                for (int x = 0; x < this.checkedListBox1.Items.Count; x++)
                {
                    this.checkedListBox1.SetItemChecked(x, true);
                }
            }
            else
            {
                for (int x = 0; x < this.checkedListBox1.Items.Count; x++)
                {
                    this.checkedListBox1.SetItemChecked(x, false);
                }
            }
        }

     }
}

 